import Vue from 'vue'
import Router from 'vue-router'
import store from '../store/';

import Index from '@/components/page/Index'
import List from '@/components/page/List'
import search from '@/components/page/search'
import hotel from '@/components/page/hotel'
import food from '@/components/page/food'

Vue.use(Router)

Router.prototype.goBack = function () {
  this.isBack = true
  window.history.go(-1)
}

const router = new Router({
  routes: [
    {
      path: '/',
      name: 'Index',
      component: Index
    },
    {
      path: '/List',
      name: 'List',
      component: List
    },
    {
      path: '/search',
      name: 'search',
      component: search
    },
    {
      path: '/hotel',
      name: 'hotel',
      component: hotel
    },
    {
      path: '/food',
      name: 'food',
      component: food
    },
  ]
})

router.beforeEach((to, from, next) => {
  // 定义一个可以记录路由路径变化的数组，这里用在vuex，其实也可以用sessionStorage,或者在window.routeChain等变量
  // 不一定要用到vuex
  let routeLength = store.state.routeChain.length;
  if(from.name=='search' || to.name=='search'){
    store.commit('setPageDirection', 'fade');
  }else{
    if (routeLength === 0) {
        store.commit('setPageDirection', 'fade');
        if (to.path === from.path && to.path === '/') {
            //当直接打开根路由的时候
            store.commit('addRouteChain', to);
        } else {
            //直接打开非根路由的时候其实生成了两个路径，from其实就是根路由
            store.commit('addRouteChain', from);
            store.commit('addRouteChain', to);
        }
    } else if (routeLength === 1) {
        store.commit('setPageDirection', 'slide-left');
        store.commit('addRouteChain', to);
    } else {
        let lastBeforeRoute = store.state.routeChain[routeLength-2];
        if (lastBeforeRoute.path === to.path) {
            store.commit('popRouteChain');
            store.commit('setPageDirection', 'slide-right');
        } else {
            store.commit('addRouteChain', to);
            store.commit('setPageDirection', 'slide-left');
        }
    }
  }
  next();
});

export default router
